<template>
    <!-- 生产数据 -->
  <div>
    <div class="flow-chart-container" v-show="showFlowChart">
      <!-- <div class="flow-title">生产流程图</div> -->
      <div class="flow-chart" ref="flowChartContainer"></div>
    </div>
    <div class="tab-container">
      <!-- 使用绝对定位将按钮放在标签页标题栏上 -->
      <div class="flow-control-btn">
        <el-button type="primary" size="small" icon="el-icon-arrow-up" circle @click="toggleFlowChart" :title="showFlowChart ? '收起流程图' : '展开流程图'"></el-button>
      </div>
      <el-tabs type="border-card" v-model="activeTab">
        <el-tab-pane label="废旧轮胎" name="废旧轮胎">
          <!-- 引用废旧轮胎组件 -->
          <waste-tire />
        </el-tab-pane>
        <el-tab-pane label="毛丝" name="毛丝">
          <!-- 引用毛丝组件 -->
          <mixed-wire />
        </el-tab-pane>
        <el-tab-pane label="钢丝" name="钢丝">
          <!-- 引用钢丝组件 -->
          <steel-wire />
        </el-tab-pane>
        <el-tab-pane label="胶粉" name="胶粉">
          <!-- 引用胶粉组件 -->
          <rubber-powder />
        </el-tab-pane>
        <el-tab-pane label="口圈" name="口圈">
          <!-- 引用口圈组件 -->
          <tire-rim />
        </el-tab-pane>
        <el-tab-pane label="橡胶沥青" name="橡胶沥青">
          <!-- 引用橡胶沥青组件 -->
          <AsphaltProductData  />
        </el-tab-pane>
        <!-- <el-tab-pane label="基质沥青" name="基质沥青" v-if="showExtra">基质沥青</el-tab-pane>
        <el-tab-pane label="SBS" name="SBS" v-if="showExtra">SBS</el-tab-pane> -->
      </el-tabs>
    </div>
  </div>
</template>

<script>
import { jsPlumb } from 'jsplumb'
// 导入所有组件
import WasteTire from '@/views/mes/bm/productData/wasteTire/index'
import MixedWire from '@/views/mes/bm/productData/mixedWire/index'
import SteelWire from '@/views/mes/bm/productData/steelWire/index'
import RubberPowder from '@/views/mes/bm/productData/rubberPowder/index'
import TireRim from '@/views/mes/bm/productData/tireRim/index'
import AsphaltProductData from '@/views/mes/bm/productData/AsphaltProductData/index'

export default {
  name: 'ProductData',
  components: {
    WasteTire,
    MixedWire,
    SteelWire,
    RubberPowder,
    TireRim,
    AsphaltProductData
  },
  data() {
    return {
      showFlowChart: true,
      showExtra: false,
      activeTab: '废旧轮胎',
      jsPlumbInstance: null,
      nodePositions: {
        // 中间一行（中轴线）
        '废旧轮胎': { x: 180, y: 150 },
        '胶粉': { x: 780, y: 150 },
        '橡胶沥青': { x: 1280, y: 150 },
        
        // 最上面一行
        '毛丝': { x: 440, y: 10 },
        '钢丝': { x: 680, y: 10 },
        '基质沥青': { x: 880, y: 10 },
        
        // 最下面一行
        '口圈': { x: 440, y: 290 },
        'SBS': { x: 880, y: 290 }
      },
      nodeColors: {
        '废旧轮胎': '#d1e5f0', // 淡蓝色
        '毛丝': '#ffb1b1',     // 稍深的红色
        '钢丝': '#ffb1b1',     // 稍深的红色
        '胶粉': '#ffb1b1',     // 稍深的红色
        '口圈': '#ffb1b1',     // 稍深的红色
        '基质沥青': '#e2f0cb', // 黄绿色
        'SBS': '#e2f0cb',      // 黄绿色
        '橡胶沥青': '#c1e1c1'  // 绿色
      },
      connections: [
        { source: '废旧轮胎', target: '毛丝' },
        { source: '废旧轮胎', target: '胶粉' },
        { source: '废旧轮胎', target: '口圈' },
        { source: '毛丝', target: '胶粉' },
        { source: '毛丝', target: '钢丝' },
        { source: '胶粉', target: '基质沥青' },
        { source: '胶粉', target: '橡胶沥青' },
        { source: '胶粉', target: 'SBS' }
      ]
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initFlowChart()
    })
  },
  updated() {
    // 组件更新时重新初始化流程图
    if (this.showFlowChart) {
      this.$nextTick(() => {
        this.initFlowChart()
      })
    }
  },
  methods: {
    toggleFlowChart() {
      this.showFlowChart = !this.showFlowChart
      if (this.showFlowChart) {
        this.$nextTick(() => {
          this.initFlowChart()
        })
      }
    },
    initFlowChart() {
      if (!this.showFlowChart) return

      const container = this.$refs.flowChartContainer
      if (!container) return

      // 清空容器
      container.innerHTML = ''
      
      // 初始化jsPlumb实例
      if (this.jsPlumbInstance) {
        this.jsPlumbInstance.reset()
      }
      
      this.jsPlumbInstance = jsPlumb.getInstance({
        Endpoint: ['Blank', { radius: 0 }],
        EndpointStyle: { fill: 'transparent', stroke: 'transparent', strokeWidth: 0 },
        PaintStyle: { stroke: '#567', strokeWidth: 3 },
        HoverPaintStyle: { stroke: '#1e88e5', strokeWidth: 4 },
        ConnectionOverlays: [
          ['Arrow', { location: 1, width: 8, length: 8, foldback: 0.8 }]
        ],
        Container: container
      })
      
      // 创建节点
      Object.keys(this.nodePositions).forEach(nodeName => {
        // 创建节点主容器
        const nodeDiv = document.createElement('div')
        nodeDiv.id = nodeName
        nodeDiv.className = 'flow-node'
        nodeDiv.setAttribute('data-node-name', nodeName)
        
        // 设置节点的位置和尺寸
        const { x, y } = this.nodePositions[nodeName]
        Object.assign(nodeDiv.style, {
          left: `${x}px`,
          top: `${y}px`,
          width: '160px',
          height: '80px',
          position: 'absolute',
          display: 'flex',
          flexDirection: 'column',
          overflow: 'hidden',
          border: '1px solid rgba(0,0,0,0.1)',
          borderRadius: '3px',
          backgroundColor: '#fff',
          boxShadow: '0 2px 6px rgba(0,0,0,0.12)'
        })
        
        // 创建节点头部
        const headerDiv = document.createElement('div')
        headerDiv.className = 'node-header'
        Object.assign(headerDiv.style, {
          backgroundColor: this.nodeColors[nodeName],
          height: '36px',
          padding: '0 6px',
          display: 'flex',
          alignItems: 'center',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          whiteSpace: 'nowrap'
        })
        
        // 头部文字
        const headerSpan = document.createElement('span')
        headerSpan.textContent = this.getShortName(nodeName)
        Object.assign(headerSpan.style, {
          fontSize: '20px',
          fontWeight: 'bold',
          color: '#333',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          whiteSpace: 'nowrap'
        })
        headerDiv.appendChild(headerSpan)
        
        // 创建节点主体
        const bodyDiv = document.createElement('div')
        bodyDiv.className = 'node-body'
        Object.assign(bodyDiv.style, {
          flex: '1',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          padding: '0 4px',
          backgroundColor: 'white',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          whiteSpace: 'nowrap'
        })
        
        // 主体文字
        const bodySpan = document.createElement('span')
        bodySpan.textContent = this.getShortName(nodeName)
        Object.assign(bodySpan.style, {
          fontSize: '20px',
          color: '#555',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          whiteSpace: 'nowrap'
        })
        bodyDiv.appendChild(bodySpan)
        
        // 组装节点
        nodeDiv.appendChild(headerDiv)
        nodeDiv.appendChild(bodyDiv)
        container.appendChild(nodeDiv)
        
        // 添加点击事件
        nodeDiv.addEventListener('click', () => {
          // 只有当点击的不是基质沥青和SBS节点时，才更改activeTab
          if (!['基质沥青', 'SBS'].includes(nodeName)) {
            this.activeTab = nodeName
          }
          
          if (['基质沥青', 'SBS'].includes(nodeName)) {
            this.showExtra = true
          }
          
          // 高亮点击的节点
          const allNodes = container.querySelectorAll('.flow-node')
          allNodes.forEach(node => node.classList.remove('node-active'))
          nodeDiv.classList.add('node-active')
        })
        
        // 使节点可拖动
        this.jsPlumbInstance.draggable(nodeName, {
          containment: container,
          grid: [5, 5],
          stop: (event) => {
            // 更新节点位置
            const { style } = event.el
            this.nodePositions[nodeName] = {
              x: parseInt(style.left),
              y: parseInt(style.top)
            }
          }
        })
      })
      
      // 添加中轴线连接（轮胎到胶粉到橡胶）
      this.$nextTick(() => {
        // 创建虚拟分支点 - 在轮胎右侧45px处
        const sourceNode = this.nodePositions['废旧轮胎'];
        const branchPoint = document.createElement('div');
        branchPoint.id = 'branch-point-tire';
        branchPoint.style.position = 'absolute';
        branchPoint.style.left = `${sourceNode.x + 160 + 45}px`; // 轮胎宽度160px + 45px偏移
        branchPoint.style.top = `${sourceNode.y + 40}px`; // 垂直居中
        branchPoint.style.width = '1px';
        branchPoint.style.height = '1px';
        branchPoint.style.background = 'transparent';
        branchPoint.style.border = 'none';
        branchPoint.style.opacity = '0';
        branchPoint.style.pointerEvents = 'none';
        container.appendChild(branchPoint);

        // 创建钢丝分支点 - 在轮胎分支点右侧250px处
        const steelBranchPoint = document.createElement('div');
        steelBranchPoint.id = 'branch-point-steel';
        steelBranchPoint.style.position = 'absolute';
        steelBranchPoint.style.left = `${sourceNode.x + 160 + 45 + 250}px`; // 轮胎宽度160px + 45px偏移 + 250px
        steelBranchPoint.style.top = `${sourceNode.y + 40}px`; // 垂直居中
        steelBranchPoint.style.width = '1px';
        steelBranchPoint.style.height = '1px';
        steelBranchPoint.style.background = 'transparent';
        steelBranchPoint.style.border = 'none';
        steelBranchPoint.style.opacity = '0';
        steelBranchPoint.style.pointerEvents = 'none';
        container.appendChild(steelBranchPoint);
        
        // 废旧轮胎 -> 分支点
        this.jsPlumbInstance.connect({
          source: '废旧轮胎',
          target: branchPoint.id,
          anchors: ['Right', 'Left'],
          paintStyle: { stroke: '#567', strokeWidth: 3 },
          hoverPaintStyle: { stroke: '#1e88e5', strokeWidth: 4 },
          connector: ['Straight'],
          overlays: [] // 移除箭头
        });

        // 分支点 -> 钢丝分支点
        this.jsPlumbInstance.connect({
          source: branchPoint.id,
          target: steelBranchPoint.id,
          anchors: ['Right', 'Left'],
          paintStyle: { stroke: '#567', strokeWidth: 3 },
          hoverPaintStyle: { stroke: '#1e88e5', strokeWidth: 4 },
          connector: ['Straight'],
          overlays: [] // 移除箭头
        });

        // 钢丝分支点 -> 钢丝（向上再右拐）
        this.jsPlumbInstance.connect({
          source: steelBranchPoint.id,
          target: '钢丝',
          anchors: [
            'Top',  // 分支点顶部
            'Left'  // 钢丝左侧
          ],
          paintStyle: { stroke: '#567', strokeWidth: 3 },
          hoverPaintStyle: { stroke: '#1e88e5', strokeWidth: 4 },
          connector: ['Flowchart', { cornerRadius: 5 }] // 使用流程图连接器实现直角拐弯
        });
        
        // 分支点 -> 毛丝（向上再右拐）
        this.jsPlumbInstance.connect({
          source: branchPoint.id,
          target: '毛丝',
          anchors: [
            'Top',  // 分支点顶部
            'Left'  // 毛丝左侧
          ],
          paintStyle: { stroke: '#567', strokeWidth: 3 },
          hoverPaintStyle: { stroke: '#1e88e5', strokeWidth: 4 },
          connector: ['Flowchart', { cornerRadius: 5 }] // 使用流程图连接器实现直角拐弯
        });
        
        // 分支点 -> 口圈（向下再右拐）
        this.jsPlumbInstance.connect({
          source: branchPoint.id,
          target: '口圈',
          anchors: [
            'Bottom',  // 分支点底部
            'Left'  // 口圈左侧
          ],
          paintStyle: { stroke: '#567', strokeWidth: 3 },
          hoverPaintStyle: { stroke: '#1e88e5', strokeWidth: 4 },
          connector: ['Flowchart', { cornerRadius: 5 }] // 使用流程图连接器实现直角拐弯
        });
        
        // 注释掉分支点到胶粉的直接连接
        // 分支点 -> 胶粉（水平连接）
        // this.jsPlumbInstance.connect({
        //   source: branchPoint.id,
        //   target: '胶粉',
        //   anchors: ['Right', 'Left'],
        //   paintStyle: { stroke: '#567', strokeWidth: 3 },
        //   hoverPaintStyle: { stroke: '#1e88e5', strokeWidth: 4 },
        //   connector: ['Straight'] // 使用直线连接器确保连接笔直
        // });
        
        // 注释掉胶粉到橡胶沥青的直接连接
        // 胶粉 -> 橡胶沥青
        // this.jsPlumbInstance.connect({
        //   source: '胶粉',
        //   target: '橡胶沥青',
        //   anchors: ['Right', 'Left'],
        //   paintStyle: { stroke: '#567', strokeWidth: 3 },
        //   hoverPaintStyle: { stroke: '#1e88e5', strokeWidth: 4 },
        //   connector: ['Straight'] // 使用直线连接器确保连接笔直
        // });
        
        // 添加钢丝分支点(250px处)到胶粉的连接
        this.jsPlumbInstance.connect({
          source: steelBranchPoint.id,
          target: '胶粉',
          anchors: ['Right', 'Left'],
          paintStyle: { stroke: '#567', strokeWidth: 3 },
          hoverPaintStyle: { stroke: '#1e88e5', strokeWidth: 4 },
          connector: ['Straight'],
          overlays: [], // 移除箭头
          detachable: false
        });
      });

      // 创建胶粉分支点 - 在胶粉右侧225px处
      const rubberBranchPoint = document.createElement('div');
      rubberBranchPoint.id = 'branch-point-rubber';
      const rubberNode = this.nodePositions['胶粉'];
      rubberBranchPoint.style.position = 'absolute';
      rubberBranchPoint.style.left = `${rubberNode.x + 160 + 225}px`; // 胶粉宽度160px + 225px偏移
      rubberBranchPoint.style.top = `${rubberNode.y + 40}px`; // 垂直居中
      rubberBranchPoint.style.width = '1px';
      rubberBranchPoint.style.height = '1px';
      rubberBranchPoint.style.background = 'transparent';
      rubberBranchPoint.style.border = 'none';
      rubberBranchPoint.style.opacity = '0';
      rubberBranchPoint.style.pointerEvents = 'none';
      container.appendChild(rubberBranchPoint);

      // 胶粉 -> 胶粉分支点
      this.jsPlumbInstance.connect({
        source: '胶粉',
        target: rubberBranchPoint.id,
        anchors: ['Right', 'Left'],
        paintStyle: { stroke: '#567', strokeWidth: 3 },
        hoverPaintStyle: { stroke: '#1e88e5', strokeWidth: 4 },
        connector: ['Straight'],
        overlays: [],
        detachable: false
      });

      // 胶粉分支点 -> 基质沥青（向上再左拐）
      this.jsPlumbInstance.connect({
        source: rubberBranchPoint.id,
        target: '基质沥青',
        anchors: [
          'Top',  // 分支点顶部
          'Right'  // 基质沥青右侧
        ],
        paintStyle: { stroke: '#567', strokeWidth: 3 },
        hoverPaintStyle: { stroke: '#1e88e5', strokeWidth: 4 },
        connector: ['Flowchart', { 
          cornerRadius: 5,
          stub: [30, 30] // 设置水平和垂直延伸的长度
        }],
        detachable: false
      });
      
      // 胶粉分支点 -> SBS（向下再左拐）
      this.jsPlumbInstance.connect({
        source: rubberBranchPoint.id,
        target: 'SBS',
        anchors: [
          'Bottom',  // 分支点底部
          'Right'  // SBS右侧
        ],
        paintStyle: { stroke: '#567', strokeWidth: 3 },
        hoverPaintStyle: { stroke: '#1e88e5', strokeWidth: 4 },
        connector: ['Flowchart', { 
          cornerRadius: 5,
          stub: [30, 30] // 设置水平和垂直延伸的长度
        }],
        detachable: false
      });

      // 胶粉分支点 -> 橡胶沥青（水平连接）
      this.jsPlumbInstance.connect({
        source: rubberBranchPoint.id,
        target: '橡胶沥青',
        anchors: ['Right', 'Left'],
        paintStyle: { stroke: '#567', strokeWidth: 3 },
        hoverPaintStyle: { stroke: '#1e88e5', strokeWidth: 4 },
        connector: ['Straight'],
        overlays: [],
        detachable: false
      });
    },
    // 获取节点的简短名称
    getShortName(name) {
      // 提取节点简称
      const shortNames = {
        '废旧轮胎': '废旧轮胎',
        '基质沥青': '基质沥青',
        '橡胶沥青': '橡胶沥青',
        '毛丝': '毛丝',
        '钢丝': '钢丝',
        '胶粉': '胶粉',
        '口圈': '口圈',
        'SBS': 'SBS'
      }
      return shortNames[name] || name
    },
    // 创建连接线上的标签
    createLabel(text) {
      return [
        ['Label', { 
          label: text, 
          location: 0.5, 
          cssClass: 'connection-label',
          id: `label-${text}` 
        }]
      ]
    }
  }
}
</script>

<style scoped>
.flow-chart-container {
  width: 100%;
  height: 380px;
  border: 1px solid #e0e7ff;
  position: relative;
  margin-bottom: 20px;
  overflow: hidden;
  background-color: #f5f9fd;
  border-radius: 6px;
  box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.05);
}

.flow-chart {
  width: 100%;
  height: 100%;
  position: relative;
}

.tab-container {
  position: relative;
}

.flow-control-btn {
  position: absolute;
  right: 15px;
  top: 8px;
  z-index: 10;
}

.flow-node {
  width: 160px !important;
  height: 80px !important;
  position: absolute;
  border-radius: 3px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  cursor: pointer;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
  overflow: hidden;
  background-color: #fff;
  z-index: 10;
  transition: all 0.25s ease;
  box-sizing: border-box;
  display: flex !important;
  flex-direction: column !important;
  padding: 0 !important;
  margin: 0 !important;
}

.flow-node:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
  z-index: 20;
}

.node-active {
  box-shadow: 0 0 0 2px #409EFF, 0 5px 15px rgba(0, 0, 0, 0.1) !important;
  z-index: 25 !important;
}

.node-header {
  height: 36px !important;
  padding: 0 6px !important;
  text-align: left;
  font-weight: bold;
  display: flex;
  align-items: center;
  color: #333;
  font-size: 20px !important;
  position: relative;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1 !important;
  box-sizing: border-box !important;
}

.node-body {
  height: 44px !important;
  padding: 0 4px !important;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: white;
  font-size: 20px !important;
  color: #555;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1 !important;
  box-sizing: border-box !important;
  flex: 1;
}

/* 给流程图添加标题 */
.flow-title {
  position: absolute;
  top: 10px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 16px;
  font-weight: bold;
  z-index: 5;
  color: #333;
}

/* 连接线上的标签样式 */
:deep(.connection-label) {
  background-color: white;
  padding: 2px 6px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  font-size: 20px;
  color: #555;
  z-index: 15;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08);
  font-weight: 500;
}
</style>